package com.maybach.workflow.core;

import com.maybach.workflow.common.api.FlowChain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by houenxun on 15/9/14.
 */
public class FlowDefineFactory {
    private static Logger logger = LoggerFactory.getLogger(FlowDefineFactory.class);
    private static Map<String, Map<Integer, FlowChain>> flowDefineMap = new HashMap<String, Map<Integer, FlowChain>>();
    private static Map<String, FlowChain> defaultFlowDefineMap = new HashMap<String, FlowChain>();

    /**
     * 根据名称和版本获取流程，如果version为空则获取默认流程
     *
     * @param name
     * @param version
     * @return
     */
    public static FlowChain getFlowDefine(String name, Integer version) {
        if (null == version) {
            return defaultFlowDefineMap.get(name);
        } else {
             Map<Integer, FlowChain> map = flowDefineMap.get(name);
            if(null == map){
                logger.error("has no flow with name= "+name+", version="+version);
                return null;
            }
            return map.get(version);
        }
    }

    /**
     * 获取所用默认的流程
     *
     * @return
     */
    public static Collection<FlowChain> getDefaultFlowChain() {
        return defaultFlowDefineMap.values();
    }

    /**
     * 注册
     * @param flowChain
     */
    public static boolean register(FlowChain flowChain) {
        /**
         * 版本为0的注册到
         */
        if(flowChain.getVersion() == 0){
            return false;
        }
        FlowChain def = defaultFlowDefineMap.get(flowChain.getName());
        /**
         * 当前名称的默认流程不存在或者版本较低 用新版本替换
         */
        if (null == def || def.getVersion() < flowChain.getVersion()) {
            defaultFlowDefineMap.put(flowChain.getName(), flowChain);
        }
        Map<Integer, FlowChain> map = flowDefineMap.get(flowChain.getName());
        if (null == map) {
            map = new HashMap<Integer, FlowChain>();
            flowDefineMap.put(flowChain.getName(), map);
        }
        if (map.containsKey(flowChain.getVersion())) {
            logger.error("重复注册, flowName={}, flowVersion={}", flowChain.getName(), flowChain.getVersion());
        }
        map.put(flowChain.getVersion(), flowChain);
        return true;
    }

}
